package com.note.service.impl;

import com.note.common.core.domain.model.LoginUser;
import com.note.common.utils.SecurityUtils;
import com.note.common.utils.uuid.IdUtils;
import com.note.domain.BaiduyunInfo;
import com.note.domain.SftpContext;
import com.note.domain.SourceLiking;
import com.note.domain.SourceScreenshots;
import com.note.dto.BaiduYunInfoResponse;
import com.note.dto.BaiduyunInfoDTO;
import com.note.mapper.BaiduyunInfoMapper;
import com.note.request.SourceSearchRequest;
import com.note.service.FilePathProductServiceI;
import com.note.service.FileSystemService;
import com.note.service.IBaiduyunInfoService;
import com.note.service.ISourceScreenshotsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-04-16
 */
@Service
public class BaiduyunInfoServiceImpl implements IBaiduyunInfoService
{
    @Autowired
    private BaiduyunInfoMapper baiduyunInfoMapper;
    @Autowired
    private FileSystemService fileSystemService;
    @Autowired
    FilePathProductServiceI filePathProductService;

    @Autowired
    ISourceScreenshotsService iSourceScreenshotsService;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public BaiduyunInfo selectBaiduyunInfoById(String id)
    {
        return baiduyunInfoMapper.selectBaiduyunInfoById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param baiduyunInfo 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<BaiduyunInfo> selectBaiduyunInfoList(BaiduyunInfo baiduyunInfo)
    {
        return baiduyunInfoMapper.selectBaiduyunInfoList(baiduyunInfo);
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param baiduyunInfo 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertBaiduyunInfo(BaiduyunInfo baiduyunInfo) throws Exception {
        BaiduyunInfo baiduyunInfoSaver = new BaiduyunInfo();
        BeanUtils.copyProperties(baiduyunInfo, baiduyunInfoSaver);
        String mainId = IdUtils.randomUUID();
        baiduyunInfoSaver.setId(mainId);
        BaiduyunInfoDTO baiduyunInfoDTO = (BaiduyunInfoDTO) baiduyunInfo;
        Date date = new Date();
        baiduyunInfoSaver.setCreateTime(date);
        baiduyunInfoSaver.setUpdateTime(date);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        baiduyunInfoSaver.setUpdateBy(loginUser.getUser().getUserId()+"");
        baiduyunInfoSaver.setCreateBy(loginUser.getUser().getUserId()+"");
        MultipartFile cover = baiduyunInfoDTO.getCover();
        if(cover != null){
            //获得上传之后的封面路径
            String coverUrl = saveCover(cover, "cover");
            baiduyunInfoSaver.setCoverUrl(coverUrl);
        }

        if(!CollectionUtils.isEmpty(baiduyunInfoDTO.getScreenshotList())){
            List<SourceScreenshots> sourceScreenshotsList = new ArrayList<>();
            for(int i = 0; i < baiduyunInfoDTO.getScreenshotList().size(); i++){
                SourceScreenshots sourceScreenshotDO = new SourceScreenshots();
                MultipartFile multipartFile = baiduyunInfoDTO.getScreenshotList().get(i);
                //得到截图的上传路径
                String screenshotUrl = saveCover(multipartFile, "screenshots");
                sourceScreenshotDO.setId(IdUtils.randomUUID());
                sourceScreenshotDO.setSourceId(baiduyunInfoSaver.getId());
                sourceScreenshotDO.setScreenshotUrl(screenshotUrl);
                sourceScreenshotDO.setScreenshotSort(i);
                String originalFilename = multipartFile.getOriginalFilename();
                sourceScreenshotDO.setScreenshotName(originalFilename);
                sourceScreenshotsList.add(sourceScreenshotDO);
            }
            iSourceScreenshotsService.batchInsert(sourceScreenshotsList);

        }

        return baiduyunInfoMapper.insertBaiduyunInfo(baiduyunInfoSaver);
    }

    /**
     * 保存封面
     * @param file 文件资源
     * @param twoLevelDirName 二级目录
     */
    private String saveCover(MultipartFile file, String twoLevelDirName) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String subbfix = originalFilename.substring(originalFilename.lastIndexOf("\\.") + 1);
        SftpContext sftpContext = new SftpContext();
        sftpContext.setUserName("baiduyun"+"/"+twoLevelDirName);
        sftpContext.setSubbfix(subbfix);
        String path = filePathProductService.productSftpPath(sftpContext);

        fileSystemService.uploadFile(path, file.getInputStream());

         return path;
    }


    /**
     * 批量删除【请填写功能名称】
     * 
     * @param ids 需要删除的【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteBaiduyunInfoByIds(String[] ids)
    {
        return baiduyunInfoMapper.deleteBaiduyunInfoByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteBaiduyunInfoById(String id)
    {
        return baiduyunInfoMapper.deleteBaiduyunInfoById(id);
    }

    @Override
    public List<BaiduYunInfoResponse> searchSourceList(SourceSearchRequest sourceSearchRequest) {
        return baiduyunInfoMapper.searchSourceList(sourceSearchRequest);
    }

    @Override
    public BaiduYunInfoResponse searchASourceDetail(String id, Long userId) {
        return baiduyunInfoMapper.searchASourceDetail(id, userId);
    }

    @Override
    public BaiduyunInfo preOrNextSource(Integer type, String classification, String id, Date createTime) {
        return baiduyunInfoMapper.preOrNextSource(type, classification, id, createTime);
    }


    @Override
    public void editSource(BaiduyunInfoDTO baiduyunInfoDTO) throws Exception {
        List<String> deleteScreenshotids = baiduyunInfoDTO.getDeleteScreenshotids();
        if(!CollectionUtils.isEmpty(deleteScreenshotids)){
            //先删掉 在页面删除的截图
            iSourceScreenshotsService.deleteSourceScreenshotsByIds(deleteScreenshotids.toArray(new String[deleteScreenshotids.size()]));
        }


        // 看有没有新增的图片。有就上传
        List<MultipartFile> screenshotList = baiduyunInfoDTO.getScreenshotList();
        if(!CollectionUtils.isEmpty(screenshotList)){
            Integer maxSort = iSourceScreenshotsService.getMaxSortScreenshotsBySourceId(baiduyunInfoDTO.getId());
            maxSort = maxSort == null ? 0 : maxSort;
            List<SourceScreenshots> sourceScreenshotsList = new ArrayList<>();
            for(int i = 0; i < screenshotList.size(); i++){
                SourceScreenshots sourceScreenshotDO = new SourceScreenshots();
                MultipartFile multipartFile = screenshotList.get(i);
                //得到截图的上传路径
                String screenshotUrl = saveCover(multipartFile, "screenshots");
                sourceScreenshotDO.setId(IdUtils.randomUUID());
                sourceScreenshotDO.setSourceId(baiduyunInfoDTO.getId());
                sourceScreenshotDO.setScreenshotUrl(screenshotUrl);
                sourceScreenshotDO.setScreenshotSort(maxSort+i+1);
                String originalFilename = multipartFile.getOriginalFilename();
                sourceScreenshotDO.setScreenshotName(originalFilename);
                sourceScreenshotsList.add(sourceScreenshotDO);
            }
            iSourceScreenshotsService.batchInsert(sourceScreenshotsList);

        }

        MultipartFile cover = baiduyunInfoDTO.getCover();
        //cover 非空，则代表有更新封面
        if(cover != null){
            //获得上传之后的封面路径，替换旧的封面
            String coverUrl = saveCover(cover, "cover");
            baiduyunInfoDTO.setCoverUrl(coverUrl);
        }
        baiduyunInfoDTO.setUpdateTime(new Date());
         baiduyunInfoMapper.updateBaiduyunInfo(baiduyunInfoDTO);

    }

    @Override
    public void deleteSource(List<String> sourceIds) {
        if(CollectionUtils.isEmpty(sourceIds)){
            return;
        }

        //先删关联的截图
        baiduyunInfoMapper.batchDeleteScreenShots(sourceIds);
        //再删资源
        baiduyunInfoMapper.batchDeleteSource(sourceIds);

    }

    @Override
    public List<BaiduyunInfo> getShufflingSourceList(String sourceId) {
        return baiduyunInfoMapper.getShufflingSourceList(sourceId);
    }

    @Override
    public void liking(SourceLiking sourceLiking) {
        baiduyunInfoMapper.liking(sourceLiking);
    }

    @Override
    public List<BaiduyunInfo> getMaxLikeSourceList(Integer num) {
        return baiduyunInfoMapper.getMaxLikeSourceList(num);
    }


}
